﻿<template>
  <!-- 顶部切换 -->
  <div class="card-btn">
    <el-button text class="login-tab" :class="mode === 'pwd' && 'is-active'" @click="setMode('pwd')"
      >密码登录</el-button
    >
    <el-divider direction="vertical" />
    <el-button text class="login-tab" :class="mode === 'sms' && 'is-active'" @click="setMode('sms')"
      >验证码登录</el-button
    >
  </div>

  <!-- 表单 -->
  <el-form ref="formRef" :model="form" :rules="rules" class="login-form" label-position="left" @keyup.enter="submit">
    <!-- 手机号 -->
    <el-form-item prop="mobile">
      <el-input size="large" v-model.trim="form.mobile" placeholder="请输入手机号" maxlength="11" clearable>
        <template #prefix><base-icon :size="14" name="iconfont-general gen-zhanghao" /></template>
      </el-input>
    </el-form-item>

    <!-- 密码登录 -->
    <template v-if="mode === 'pwd'">
      <el-form-item prop="password">
        <el-input
          size="large"
          v-model="form.password"
          :type="showPwd ? 'text' : 'password'"
          maxlength="32"
          placeholder="请输入密码"
          show-password
          @visible-change="showPwd = $event"
        >
          <template #prefix><base-icon :size="14" name="iconfont-general gen-suo" /></template>
        </el-input>
      </el-form-item>
    </template>

    <!-- 图形验证码（两种模式都会用到） -->
    <div class="form-row-2col">
      <el-form-item prop="imgCode" class="grow">
        <el-input size="large" v-model.trim="form.imgCode" placeholder="请输入安全校验码" maxlength="4" clearable>
          <template #prefix><base-icon :size="14" name="iconfont-general gen-yanzhengma" /></template>
        </el-input>
      </el-form-item>
      <el-image class="captcha-img" :src="captchaImg" fit="contain" @click="refreshCaptcha">
        <template #error><div class="captcha-fallback" @click.stop="refreshCaptcha">点击刷新</div></template>
      </el-image>
    </div>

    <!-- 短信登录：短信码 + 获取按钮 -->
    <template v-if="mode === 'sms'">
      <el-form-item prop="smsCode">
        <el-input size="large" v-model.trim="form.smsCode" placeholder="请输入验证码" maxlength="6">
          <template #prefix><base-icon :size="14" name="iconfont-general gen-yanzhengma" /></template>
          <template #suffix>
            <el-button
              text
              :disabled="smsSending || countdown > 0"
              @click="sendSms"
              style="width: 80px; color: var(--bd); font-size: 14px"
            >
              {{ countdown > 0 ? `重新获取${countdown}s` : "获取验证码" }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
    </template>

    <!-- 提交 -->
    <el-form-item class="submit-item">
      <el-button class="btn-login btn--rect" type="primary" :loading="loading" @click="submit" :disabled="!canSubmit"
        >登录</el-button
      >
    </el-form-item>

    <!-- 其它操作 -->
    <div class="extras">
      <el-button text class="link" @click="$emit('onboard', form.mobile)">商家入驻</el-button>
      <el-button text class="link" @click="$emit('forget', form.mobile)">忘记密码？</el-button>
    </div>
  </el-form>
</template>

<script setup>
  import { SMS_TYPE } from "@/utils/const";
  // 父传的 loading（登录提交中的加载）
  const props = defineProps({ loading: { type: Boolean, default: false } });
  const emit = defineEmits(["submit", "forget", "onboard", "send-sms", "mode-change"]);

  const mode = ref("pwd"); // 'pwd' | 'sms'
  function setMode(m) {
    if (mode.value !== m) {
      mode.value = m;
      emit("mode-change", m);
      refreshCaptcha();
      resetForm();
    }
  }

  const formRef = ref();
  const showPwd = ref(false);

  // 表单数据
  const form = reactive({ mobile: "", password: "", imgCode: "", smsCode: "", captchaId: "" });
  function resetForm() {
    // 清空数据
    Object.assign(form, { mobile: "", password: "", imgCode: "", smsCode: "", captchaId: "" });
    // 重置校验
    formRef.value?.resetFields();
  }
  // 校验
  const rules = {
    mobile: [
      { required: true, message: "请输入手机号", trigger: "blur" },
      { validator: (_, v, cb) => (/^1\d{10}$/.test(v) ? cb() : cb(new Error("手机号格式错误"))), trigger: "blur" },
    ],
    password: [
      { required: () => mode.value === "pwd", message: "请输入密码", trigger: "blur" },
      { min: 6, max: 32, message: "密码长度 6~32", trigger: "blur" },
    ],
    imgCode: [{ required: true, message: "请输入安全校验码", trigger: "blur" }],
    smsCode: [
      { required: () => mode.value === "sms", message: "请输入验证码", trigger: "blur" },
      {
        validator: (_, v, cb) =>
          mode.value === "sms" ? (/^\d{4,6}$/.test(v || "") ? cb() : cb(new Error("验证码格式错误"))) : cb(),
        trigger: "blur",
      },
    ],
  };

  // 图形码（就地实现：seed + url）
  const captchaImg = ref("");
  async function refreshCaptcha() {
    try {
      // 你的拦截器成功分支目前返回的是 axios Response（return res）
      const res = await Api.login.GetCodeImg(); // 若你是 Api.login.GetCodeImg()，改成对应导入即可
      console.error("refreshCaptcha res ===", res);
      const payload = res.data ?? res; // 兼容
      const data = payload.data ?? payload; // 兼容
      form.captchaId = data.cid || ""; // 保存 cid
      captchaImg.value = data.imageBase64 || ""; // 显示图片
    } catch (e) {
      // 换一张失败了就清空
      form.captchaId = "";
      captchaImg.value = "";
      console.error("refreshCaptcha error ===", e);
    }
  }

  // 短信倒计时（就地实现）
  const countdown = ref(0);
  const smsSending = ref(false);
  let timer = null;
  const startCountdown = (sec = 60) => {
    countdown.value = sec;
    clearInterval(timer);
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer);
        timer = null;
      }
    }, 1000);
  };
  // 进来先拉一张
  onMounted(refreshCaptcha);
  onBeforeUnmount(() => timer && clearInterval(timer));

  // 是否可提交
  const canSubmit = computed(() => {
    const phoneOk = /^1\d{10}$/.test(form.mobile);
    if (mode.value === "pwd") return phoneOk && !!form.imgCode && (form.password?.length || 0) >= 6;
    return phoneOk && !!form.imgCode && /^\d{4,6}$/.test(form.smsCode || "");
  });

  // 发送短信：仅校验手机号和图形码，通过后把动作抛给父级（或你也可以在这里直接调接口）
  async function sendSms() {
    const ok = await formRef.value
      .validateField(["mobile", "imgCode"])
      .then(() => true)
      .catch(() => false);
    if (!ok) return;

    // 没有 captchaId 先刷新一次
    if (!form.captchaId) {
      await refreshCaptcha();
      if (!form.captchaId) return;
    }

    try {
      smsSending.value = true;
      await Api.login.SendSms({
        mobile: form.mobile,
        cid: form.captchaId, // 验证码ID
        code: form.imgCode, // 图形码填写到 code
        type: SMS_TYPE.LOGIN,
      });
      $msg.success("验证码已发送");
      startCountdown(60);
    } catch (e) {
      refreshCaptcha();
      form.imgCode = "";
    } finally {
      smsSending.value = false;
    }
  }

  // 提交：把模式与数据一次性抛给父
  async function submit() {
    console.log("[LoginForm] click submit");
    const useFields = mode.value === "pwd" ? ["mobile", "imgCode", "password"] : ["mobile", "imgCode", "smsCode"];
    const ok = await formRef.value
      .validateField(useFields)
      .then(() => true)
      .catch(() => false);
    console.log("[LoginForm] validate ok?", ok, { ...form, mode: mode.value });
    if (!ok) return;
    emit("submit", { ...form, mode: mode.value });
  }

  defineExpose({ form, mode, refreshCaptcha });
</script>

<style scoped>
  /* 顶部 Tabs 行（适配你之前的样式） */
  .card-btn {
    margin-top: 16px;
    display: flex;
    width: 100%;
    height: 9.5%;
    align-items: center;
    justify-content: center;
    gap: 0;
  }
  :deep(.el-divider--vertical) {
    margin: 0 3%;
    height: 18px;
  }
  .login-tab {
    padding: 0;
    font-weight: 400;
    font-size: 16px;
    color: var(--ct3) !important;
  }
  .is-active {
    font-weight: 500;
    color: var(--bd) !important;
  }

  /* 表单公共 */
  .login-form {
    z-index: 1;
    width: 76%;
    margin-top: 4%;
    display: flex;
    flex-direction: column;
    gap: 6px;
  }
  .form-row-2col {
    display: flex;
    gap: 12px;
    align-items: center;
    margin-bottom: 18px;
  }
  .grow {
    flex: 1;
    margin-bottom: 0;
  }
  .captcha-img {
    width: 120px;
    height: 40px;
    cursor: pointer;
  }
  .captcha-fallback {
    width: 120px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;
    color: #999;
  }
  .submit-item {
    margin: 0;
  }
  .btn-login {
    width: 100%;
    height: 40px;
    font-size: 16px;
  }
  .extras {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .link {
    padding: 0;
    color: var(--bd);
  }
</style>
